<template>
  <div style="padding: 0px 15px;" class="overflowY">
    <div class="searchGroup_list" style="padding: 0px 0px 10px 0px;margin: 0px 0px 0px 0px;">
      <el-row :gutter="20">
        <el-col :sm="6" :xl="4">
          <div class="searchBoxList">
            <el-row>
              <el-col :span="6">
                <span class="searchListName">被授权人: </span>
              </el-col>
              <el-col :span="16">
                <el-input size="small" v-model="queryCondition.toUserName" placeholder="请输入被授权人" :clearable="true"></el-input>
              </el-col>
            </el-row>
          </div>
        </el-col>
        <el-col :sm="12" :xl="12">
          <div class="searchBoxList">
            <el-row>
              <el-col :span="5">
                <span class="searchListName">授权开始时间:</span>
              </el-col>
              <el-col :span="19">
                <el-date-picker v-model="queryCondition.beginTimeFrom" size="small" type="datetime"
                                placeholder="选择日期时间" default-time="00:00:00" value-format="yyyyMMddHHmmss">
                </el-date-picker>
                &nbsp;至&nbsp;
                <el-date-picker v-model="queryCondition.beginTimeTo" size="small" type="datetime"
                                placeholder="选择日期时间" default-time="23:59:59" value-format="yyyyMMddHHmmss">
                </el-date-picker>
              </el-col>
            </el-row>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :sm="6" :xl="4">
          <div class="searchBoxList">
            <el-row>
              <el-col :span="6">
                <span class="searchListName">状态: </span>
              </el-col>
              <el-col :span="16">
                <el-select v-model="queryCondition.status" placeholder="请选状态" size="small" :clearable="true">
                  <el-option
                    v-for="item in statusOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-col>
            </el-row>
          </div>
        </el-col>
        <el-col :sm="12" :xl="12">
          <div class="searchBoxList">
            <el-row>
              <el-col :span="5">
                <span class="searchListName">授权结束时间:</span>
              </el-col>
              <el-col :span="19">
                <el-date-picker v-model="queryCondition.endTimeFrom" size="small" type="datetime" :editable="false"
                                placeholder="选择日期时间" default-time="00:00:00" value-format="yyyyMMddHHmmss">
                </el-date-picker>
                &nbsp;至&nbsp;
                <el-date-picker v-model="queryCondition.endTimeTo" size="small" type="datetime" :editable="false"
                                placeholder="选择日期时间" default-time="23:59:59" value-format="yyyyMMddHHmmss">
                </el-date-picker>
              </el-col>
            </el-row>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <div style="display: inline-block;text-align: left;width: 100%;padding-top: 11px;">
            <el-button type="primary" size="mini" class="size" icon="el-icon-plus" @click="toAdd">新增</el-button>
          </div>
        </el-col>
        <el-col :span="12">
          <div style="display: inline-block;text-align: right;width: 100%;padding-top: 11px; padding-right: 5px">
            <el-button type="primary" size="mini" class="size" icon="el-icon-search" @click="fetchData">搜索</el-button>
          </div>
        </el-col>
      </el-row>
    </div>

    <div style="position: relative;border: 1px solid #ccc;padding:0px 0px 54px 0px;margin:0px 0px 0px 0px;position: relative;">
      <el-table ref="singleTable" :data="tableData" tooltip-effect="dark" @row-contextmenu="rowContextmenu" @cell-dblclick="cellClick" @row-click="rowClick"
                @sort-change="sortChange" @current-change="handleCurrentChange" :highlight-current-row="true" height="340" style="width: 100%">
        <el-table-column label="序号" width="50" align="center">
          <template slot-scope="scope">
            <span>{{scope.$index + (pagingArgs.currentPageNo - 1) * queryArgs.rowBounds.limit + 1}}</span>
          </template>
        </el-table-column>
        <el-table-column label="被授权人" prop="toUserName" width="150" align="center" sortable="custom"></el-table-column>
        <el-table-column label="授权开始时间" prop="beginTime" width="150" align="center" sortable="custom"></el-table-column>
        <el-table-column label="授权结束时间" prop="endTime" width="150" align="center" sortable="custom"></el-table-column>
        <el-table-column label="是否所有公司单据" prop="isAllCorp" width="200" align="center" sortable="custom">
          <template slot-scope="scope">
            <span>{{scope.row.isAllCorp | trueOrFalseFilter}}</span>
          </template>
        </el-table-column>
        <el-table-column label="授权单据所在公司" prop="busiCorpName" width="200" align="left" sortable="custom" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="是否所有业务" prop="isAllBusi" width="200" align="center" sortable="custom">
          <template slot-scope="scope">
            <span>{{scope.row.isAllBusi | trueOrFalseFilter}}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status" width="100" align="center" sortable="custom">
          <template slot-scope="scope">
            <span>{{scope.row.status | statusFilter}}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template slot-scope="scope">
            <div class="tableBtnBox">
              <el-tooltip class="item" effect="dark" content="编辑" placement="top">
                <el-button class="buttonSize" type="primary" size="mini" @click="toEdit(scope.row)" icon="el-icon-edit" circle></el-button>
              </el-tooltip>
              <el-tooltip v-if="scope.row.status==='0'" class="item" effect="dark" content="禁用" placement="top">
                <el-button class="buttonSize" type="warning" size="mini" @click="closeRecord(scope.row)" icon="el-icon-circle-close" circle></el-button>
              </el-tooltip>
              <el-tooltip v-if="scope.row.status==='1'" class="item" effect="dark" content="启用" placement="top">
                <el-button class="buttonSize" type="info" size="mini" @click="openRecord(scope.row)" icon="el-icon-circle-check" circle></el-button>
              </el-tooltip>
              <el-tooltip  class="item" effect="dark" content="删除" placement="top">
                <el-button class="buttonSize" type="danger" size="mini" @click="deleteRecord(scope.row)" icon="el-icon-delete" circle></el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div style="position: absolute;bottom:0;left: 10px;">
        <paging :size-change="pageSizeChange" :current-change="pagingQuery" :page-sizes="pageSizes" :total-num="pagingArgs.totalCount"></paging>
      </div>
    </div>
    <el-dialog title="授权代理详细" :visible.sync="detailIsDisplay" width="60%" :close-on-click-modal="false" :destroy-on-close="true"
               v-if="detailIsDisplay" top="30px" custom-class="myDialog" @close="fetchData">
      <wf-busi-agent-detail :componentCustomProps="componentCustomProps" @closeComponent="closeDialogPage"></wf-busi-agent-detail>
    </el-dialog>
  </div>
</template>

<script>
import paging from '@/components/demoAssembly/paging' // 分页
import { queryListExt as queryList, updateRecord, deleteRecord } from '@/api/workFlowManage/wfBusiAgent'
import { default as wfBusiAgentDetail } from '@/views/workFlowManage/workFlowBusiAgent/components/wfBusiAgentDetail'

const statusOptions = [
  {
    value: '0',
    label: '启用'
  },
  {
    value: '1',
    label: '禁用'
  }
]

const trueOrFalseOptions = [
  {
    value: '0',
    label: '否'
  },
  {
    value: '1',
    label: '是'
  }
]

const statusKeyValue = statusOptions.reduce((acc, cur) => {
  acc[cur.value] = cur.label
  return acc
}, {})
const trueOrFalseKeyValue = trueOrFalseOptions.reduce((acc, cur) => {
  acc[cur.value] = cur.label
  return acc
}, {})

export default {
  name: 'wfBusiAgentListCom',
  data() {
    return {
      pageSizes: [10, 20, 30, 40],
      // 分页参数
      pagingArgs: {
        currentPageNo: 1,
        totalCount: 0
      },
      tableData: [], // 列表数据
      queryArgs: {
        sort: [
          {
            property: 'lastModifyTime',
            direction: 'DESC'
          }
        ],
        rowBounds: {
          offset: 0,
          limit: 10
        }
      },
      // 查询参数
      queryCondition: {
        toUserName: '',
        beginTimeFrom: '',
        beginTimeTo: '',
        endTimeFrom: '',
        endTimeTo: '',
        status: ''
      },
      statusOptions: statusOptions,
      trueOrFalseOptions: trueOrFalseOptions,
      statusKeyValue: {},
      trueOrFalseKeyValue: {},
      curUserId: this.$store.state.user.userid,
      recordId: '',
      openType: '',
      componentCustomProps: {},
      selectRecord: null,
      detailIsDisplay: false
    }
  },
  watch: {
    // 普通的watch监听通的watch监听
  },
  computed: {

  },
  filters: {
    statusFilter(target) {
      return statusKeyValue[target]
    },
    trueOrFalseFilter(target) {
      return trueOrFalseKeyValue[target]
    }
  },
  components: {
    paging,
    wfBusiAgentDetail
  },
  /**
   * 组件创建完成后，查询列表数据
   */
  created() {

  },
  mounted() {
    this.fetchData()
  },
  methods: {
    rowClick() {
      // 行单击事件
    },
    cellClick(row, column, cell, event) {
      // 列单击事件
    },
    rowContextmenu(row, column, e) {
      // 右键菜单
      window.event.returnValue = false
    },
    pageSizeChange(val) {
      this.queryArgs.rowBounds.limit = val
      this.queryArgs.rowBounds.offset = 0
      this.pagingArgs.currentPageNo = 1
      this.fetchData()
    },
    sortChange(col) {
      //
      if (col.prop) {
        let tempDirection = 'ASC'
        if (col.order === 'descending') {
          tempDirection = 'DESC'
        }
        const sort = {
          property: col.prop,
          direction: tempDirection
        }
        this.queryArgs.sort = []
        this.queryArgs.sort.push(sort)
        this.fetchData()
      }
    },
    pagingQuery(val) { // 分页
      this.queryArgs.rowBounds.offset = (val - 1) * this.queryArgs.rowBounds.limit
      this.pagingArgs.currentPageNo = val
      this.fetchData()
    },
    buildQueryConditions() {
      let tempQueryCondition = []

      // 删除状态
      tempQueryCondition.push({
        property: 'deleteStatus',
        type: 'NE',
        value: '1'
      })

      for (let key in this.queryCondition) {
        let queryValue = this.queryCondition[key]
        if (queryValue != null && queryValue !== '') {
          let queryProperty = key
          let type = 'LIKE'
          if (key === 'beginTimeFrom') {
            queryProperty = 'beginTime'
            type = 'GE'
          } else if (key === 'beginTimeTo') {
            queryProperty = 'beginTime'
            type = 'LE'
          } else if (key === 'endTimeFrom') {
            queryProperty = 'endTime'
            type = 'GE'
          } else if (key === 'endTimeTo') {
            queryProperty = 'endTime'
            type = 'LE'
          } else if (key === 'status') {
            type = 'EQ'
          }
          tempQueryCondition.push({
            property: queryProperty,
            type: type,
            value: queryValue
          })
        }
      }
      return tempQueryCondition
    },
    clearQueryConditions() {
      for (let key in this.queryCondition) {
        this.queryCondition[key] = ''
      }
    },
    fetchData() { // 获取内容
      this.queryArgs.curUserId = this.curUserId
      this.queryArgs.condition = this.buildQueryConditions()
      queryList(this.queryArgs).then(res => {
        let records = res.data.data.records
        if (records) {
          records.forEach((item, index) => {
            // 格式化时间
            item.beginTime = this.timeFormat(item.beginTime)
            item.endTime = this.timeFormat(item.endTime)
            item.createTime = this.timeFormat(item.createTime)
            item.lastModifyTime = this.timeFormat(item.lastModifyTime)

            // item.statusValue = item.status
            // this.statusOptions.forEach((statusItem, statusIndex) => {
            //   if (item.status === statusItem.value) {
            //     item.status = statusItem.label
            //   }
            // })
            // this.deleteStatusOptions.forEach((statusItem, statusIndex) => {
            //   if (item.deleteStatus === statusItem.value) {
            //     item.deleteStatus = statusItem.label
            //   }
            // })
          })
        }
        this.tableData = records
        this.pagingArgs.totalCount = res.data.count
        this.selectRecord = null
      }).catch(() => {

      })
    },
    handleCurrentChange(currentRow, oldCurrentRow) {
      //
      this.selectRecord = currentRow
    },
    toAdd() {
      this.detailIsDisplay = true
      this.componentCustomProps.busiId = ''
      this.componentCustomProps.openType = 'add'
    },
    toEdit(record) {
      this.detailIsDisplay = true
      this.componentCustomProps.busiId = record.id
      this.componentCustomProps.openType = 'edit'
    },
    // toView(record) {
    //   this.viewIsDisplay = true
    //   this.componentCustomProps.busiId = record.id
    //   this.componentCustomProps.openType = 'view'
    // },
    deleteRecord(record) {
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        let args = {}
        args.id = record.id
        deleteRecord(args).then(res => {
          this.fetchData()
          this.loading = false
          if (res.data.success) {
            this.$message({
              type: 'success',
              message: '删除成功！'
            })
          } else {
            this.$message({
              type: 'error',
              message: '删除失败！' + res.data.message
            })
          }
        }).catch((err) => {
          console.log(err)
          this.$message({
            type: 'error',
            message: '删除异常！'
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    openRecord(record) {
      this.loading = true
      let args = {
        // id: record.id,
        status: '0'
      }
      updateRecord(record.id, args).then(res => {
        this.fetchData()
        this.loading = false
        if (res.data.success) {
          this.$message({
            type: 'success',
            message: '启用成功！'
          })
        } else {
          this.$message({
            type: 'error',
            message: '启用失败！' + res.data.message
          })
        }
      }).catch((err) => {
        console.log(err)
        this.$message({
          type: 'error',
          message: '启用异常！'
        })
      })
    },
    closeRecord(record) {
      this.loading = true
      let args = {
        // id: record.id,
        status: '1'
      }
      updateRecord(record.id, args).then(res => {
        this.fetchData()
        this.loading = false
        if (res.data.success) {
          this.$message({
            type: 'success',
            message: '禁用成功！'
          })
        } else {
          this.$message({
            type: 'error',
            message: '禁用失败！' + res.data.message
          })
        }
      }).catch((err) => {
        console.log(err)
        this.$message({
          type: 'error',
          message: '禁用异常！'
        })
      })
    },
    timeFormat(time) {
      let tempDate = time
      try {
        if (time && time.length > 8) {
          tempDate = time.substring(0, 4) + '-' + time.substring(4, 6) + '-' + time.substring(6, 8)
          tempDate += ' ' + time.substring(8, 10) + ':' + time.substring(10, 12) + ':' + time.substring(12, 14)
        }
      } catch (e) {
        //
        console.info(e)
      }
      return tempDate
    },
    closeDialogPage() {
      this.fetchData()
      this.detailIsDisplay = false
    }
  }
}
</script>
<style scoped>

  .size{
    padding:4px;
  }

  .searchBoxList{
    margin-top: 10px;
  }
  .searchGroup_list .searchListName{
    font-size: 14px;
    color: #333333;
    display: inline-block;
    vertical-align: middle;
    line-height: 32px;
    width: 100%;
    text-align: right;
    padding-right: 8px;
  }

  .myDialog{
    padding: 0px;
  }

</style>

